package com.dk.assertion;

import com.alibaba.fastjson.JSON;
import com.dk.domain.ApiAutoTestEntity;
import com.dk.domain.assertion.CheckPointEntity;
import com.dk.domain.assertion.DbCheckEntity;
import com.dk.domain.assertion.ResCheckEntity;
import com.dk.enumerate.DkRuleEnum;
import com.dk.exception.ExcelDataException;
import com.dk.util.log.Log;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * jsonpath验证断言实现节点
 */
public class JsonPathCheckLink extends AssertChain{
    /**
     * 具体jsonpath验证断言实现
     * @param apiAutoTestEntity 检查点对象
     * @return
     */
    @Override
    public ApiAutoTestEntity assertBody(ApiAutoTestEntity apiAutoTestEntity) {
        //最终返回结果
        AtomicBoolean result = new AtomicBoolean(true);
        //获取检查点对象
        CheckPointEntity checkPointEntity = JSON.parseObject(apiAutoTestEntity.getCheckPoint(),CheckPointEntity.class);
        //获取响应校验集合
        List<ResCheckEntity> resCheckList = checkPointEntity.getResCheck();
        //获取数据库校验集合
        List<DbCheckEntity> dbCheckList = checkPointEntity.getDbCheck();

        //当响应校验集合不为空时，遍历集合筛选出
        if(resCheckList!=null&&resCheckList.size()!=0){
            resCheckList.stream().filter(resCheckEntity -> resCheckEntity.getCheckType().equals(DkRuleEnum.ASSERT_TYPE_JSONPATH.getValue())).forEach(resCheckEntity->{
                if(resCheckEntity.getCheckMain().toUpperCase().equals(DkRuleEnum.BODY.getValue())){
                    Log.info("---【用例断言】:开始执行jsonPath断言");
                    Map<String,String> targetResult = analysisJsonPathTargetResult(resCheckEntity.getTargetResult());
                    for(String jsonPath:targetResult.keySet()){
                        Log.info("---【用例断言】:断言响应体:"+apiAutoTestEntity.getResBody()+"\njsonPath:"+jsonPath+",\n目标值:"+targetResult.get(jsonPath));
                        result.set(AssertUtil.assertJsonPath(apiAutoTestEntity.getResBody(),jsonPath,targetResult.get(jsonPath)));
                        Log.info("---【用例断言】:断言通过");
                    }
                }else{
                    try {
                        throw new ExcelDataException("---【error】:checkPoint字段的resCheck的CheckMain不存在或者header使用了jsonPath提取:请检查测试数据,CaseNum:"+apiAutoTestEntity.getCaseNum()+";");
                    } catch (ExcelDataException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        return apiAutoTestEntity;
    }

    /**
     * 解析jsonPath目标结果公式
     * @param TargetResult 需要解析的目标结果
     * @return map
     */
    public static Map<String,String> analysisJsonPathTargetResult(String TargetResult){
        String[] checks = TargetResult.split("&&");
        Map<String,String> result = new HashMap<>();
        if(checks.length==0){
            Log.error("---【error】:"+TargetResult+"表达式格式错误,请检查测试数据(&&分隔符)");
        }else{
            List<String> checkList = Arrays.asList(checks);
            checkList.stream().forEach(str->{
                String[] s = str.split("==");
                if(s.length==0){
                    Log.error("---【error】:"+TargetResult+"表达式格式错误,请检查测试数据(==分隔符)");
                }else{
                    result.put(s[0].substring(1,s[0].length()-1),s[1]);
                }
            });
        }
        return result;
    }
}
